package com.ruoyi.security.config;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.security.common.R;
import com.ruoyi.security.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Spring security 登录失败后返回一串json
 */
@Component("MyAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    LoginService loginService;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        System.out.println("登录失败后~");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().append(JSON.toJSON(R.error("登陆失败")).toString());
    }
}
